<?php
require_once('Model/SiteManage.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
class Model_FileManager
{
    var $sys;
    
    public function __construct()
    {
        $this->sys = new Model_SiteManage();
    }
    //
    public function insert($data)
    {
        $db = new Model_DB();
        return $db->insert('M_FILE_MANAGER', $data);
    }
    public function update($id, $data)
    {
        $db = new Model_DB();
        return $db->update($id, 'M_FILE_MANAGER', $data);
    }
    public function get($id)
    {
        $db = new Model_DB();
        $sql = sprintf("select * from M_FILE_MANAGER where id = " . $db->escape($id) . " and enabled = 1");
        $db->query($sql);
        return $db->fetch();
    }
    public function getListCount($data)
    {
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        $sql   = "select count(*) from M_FILE_MANAGER";
        $sql  .= (!empty($where) ? " where ".implode(' AND ', $where) : "");
        $db->query($sql);
        if ($db->res){
            return array_shift($res = $db->fetch());
        }
        return false;
    }
    public function getList($data, $orderby = 'id asc', $limit = '', $offset = '')
    {
        $list  = array();
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        $sql   = "select * from M_FILE_MANAGER";
        $sql  .= (!empty($where) ? " where ".implode(' AND ', $where) : "") . (!empty($orderby) ? " order by {$orderby}" : "") . (!empty($limit) ? " limit {$limit}" : "") . (!empty($offset) ? " offset {$offset}" : "");
        $db->query($sql);
        if ($db->res){
            while($res = $db->fetch()){
                if(isset($res['id'])){
                    $list[$res['id']] = $res;
                }
                else{
                    $list[] = $res;
                }
            }
        }
        return $list;
    }
    /*
    public function getReleaseList($data, $orderby = 'id asc', $limit = '', $offset = '')
    {
        //$data['enabled'] = 1;
        //$data['status']  = 1;
        
        $where = array();
        $where[] = 'enabled = 1';
        $where[] = 'status = 1';
        $where[] = 'st_datetime <= current_timestamp';
        $where[] = 'ed_datetime > current_timestamp';
        
        $db    = new Model_DB();
        $list  = $db->getList('M_FILE_MANAGER', $where, $orderby, $limit, $offset);
        return $list;
    }
    */
    //
    private function createSearchCondition($data, $prefix = '')
    {
        $db    = new Model_DB();
        $where = array();
        if ($prefix != ''){
            $prefix = $prefix . '.';
        }
        $where[] = "{$prefix}enabled = 1";
        $where[] = "{$prefix}site_id = ". $this->sys->getCurrentSiteID();
        foreach($db->getFieldList('M_FILE_MANAGER') as $key => $_){
            if (isset($data[$key]) && !empty($data[$key])){
                if (is_array($data[$key])){
                    $values = array();
                    foreach ($data[$key] as $value){
                        $values[] = $db->escape($value);
                    }
                    $w = array();
                    foreach($values as $value){
                        if ($key == 'tag' || $key == 'title'){
                            $w[] = "{$prefix}{$key} collate utf8_unicode_ci like '%{$value}%'";
                        }
                        else{
                            $w[] = "{$prefix}{$key} = '{$value}'";
                        }
                    }
                    $where[] = "(". implode(" OR ", $w) .")";
                }
                else{
                    $value = $db->escape($data[$key]);
                    if ($key == 'tag' || $key == 'title'){
                        $where[] = "{$prefix}{$key} collate utf8_unicode_ci like '%{$value}%'";
                    }
                }
            }
        }
        return $where;
    }
    /*
    public function validate(&$data, &$err)
    {
        $validate = new Model_Validate();
        // required
        $keys = explode(',', 'status,no,class_id,category_id,name,st_date');
        foreach($keys as $key){
            if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                $err[$key]['NotEmpty'] = true;
            }
        }
        // int
        $keys = explode(',', 'price,walk_time,income,unit_price,numbers,stories,floor,management_cost,repairs_cost,rent,building_land_ratio,floor_area_ratio');
        foreach($keys as $key){
            if ($data[$key] != '' && $validate->Int($data[$key])){
                $err[$key]['Int'] = true;
            }
        }
        // float
        $keys = explode(',', 'interest,land_area,building_area');
        foreach($keys as $key){
            if ($data[$key] != '' && $validate->Float($data[$key])){
                $err[$key]['Float'] = true;
            }
        }
        // date
        $keys = explode(',', 'st_date,ed_date');
        foreach($keys as $key){
            if (isset($data[$key]) && $data[$key] != '' && $validate->Date($data[$key])){
                $err[$key]['Date'] = true;
            }
        }
        // other
        if(!isset($err['st_date']) && !isset($err['ed_date']) && $data['ed_date'] != ''){
            if($data['st_date'] > $data['ed_date']){
                $err['st_date']['Other'] = true;
            }
        }
        
        return empty($err);
    }
    */
    //
    public function getFormKeys()
    {
        $db = new Model_DB();
        return array_keys($db->getFieldList('M_FILE_MANAGER'));
    }
    //　状態
    public function getStatusMap()
    {
        $map    = array();
        $map[0] = '非公開';
        $map[1] = '公開';
        $map[2] = '仮登録';
        return $map;
    }
    public function getStatusName($id)
    {
        $map = $this->getStatusMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
}
?>